<template>
	<view :style="{ width: xzWidth + 'px', height: xzHeight + 'px'}">
		<canvas :style="{ width: xzWidth + 'px', height: xzHeight + 'px' }" canvas-id="myCanvas" @tap="newCanvas">
		</canvas>
	</view>
</template>

<script>
	var ctx;
	export default {
		props: {
			xzWidth: {
				type: Number,
				default: 150
			},
			xzHeight: {
				type: Number,
				default: 48
			},
			xzCount: {
				type: Number,
				default: 4
			}
		},
		data() {
			return {
				text: ''
			};
		},
		mounted() {
			this.getCanvas();
		},
		methods: {
			newCanvas() {
				this.getCanvas();
			},
			getCanvas() {
				var that = this
				ctx = uni.createCanvasContext('myCanvas', this);
				ctx.fillStyle = randomColor(180, 240);
				ctx.fillRect(0, 0, that.xzWidth, that.xzHeight);
				var arr;
				var text = '';
				// var str = 'ABCEFGHJKLMNPQRSTWXY123456789';
				var str = '123456789';
				for (var i = 0; i < that.xzCount; i++) {
					var txt = str[randomNum(0, str.length)];
					ctx.fillStyle = randomColor(50, 160);
					ctx.font = randomNum(20, 26) + 'px SimHei';
					var x = 10 + i * 20;
					var y = randomNum(25, 30);
					var deg = randomNum(-30, 30);
					ctx.translate(x, y);
					ctx.rotate((deg * Math.PI) / 180);
					ctx.fillText(txt, 5, 0);
					text = text + txt;
					ctx.rotate((-deg * Math.PI) / 180);
					ctx.translate(-x, -y);
				}
				for (var i = 0; i < 4; i++) {
					ctx.strokeStyle = randomColor(40, 180);
					ctx.beginPath();
					ctx.moveTo(randomNum(0, that.xzWidth), randomNum(0, that.xzHeight));
					ctx.lineTo(randomNum(0, that.xzWidth), randomNum(0, that.xzHeight));
					ctx.stroke();
				}
				for (var i = 0; i < 20; i++) {
					ctx.fillStyle = randomColor(0, 255);
					ctx.beginPath();
					ctx.arc(randomNum(0, that.xzWidth), randomNum(0, that.xzHeight), 1, 0, 2 * Math.PI);
					ctx.fill();
				}
				ctx.draw(false, function() {
					that.$emit('result', {
						detail: {
							text
						}
					});
				});
			}
		}
	};

	function randomNum(min, max) {
		return Math.floor(Math.random() * (max - min) + min);
	}

	/**生成一个随机色**/
	function randomColor(min, max) {
		var r = randomNum(min, max);
		var g = randomNum(min, max);
		var b = randomNum(min, max);
		return 'rgb(' + r + ',' + g + ',' + b + ')';
	}
</script>